﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

namespace XFFSM
{
    public class ParamLayer : GraphLayer
    {

        #region 字段
        private ReorderableList reorderableList;
        private Vector2 scrollView;

        // 参数区域
        private Rect paramLabelRect;
        private Rect paramValueRect;
        const float param_value_width = 50f;
        const float param_value_padding = 2f;

        private bool isRenaming = false;
        private string newName;

        #endregion

        #region 重写方法

        public override void OnGUI(Rect rect)
        {
            base.OnGUI(rect);

            EditorGUI.DrawRect(rect, ColorConst.ParaBackground);
            GUI.Box(rect, string.Empty, GUI.skin.GetStyle("CN Box"));

            if (this.Context.RuntimeFSMController == null) return;

            if (reorderableList == null) {
                reorderableList = new ReorderableList(this.Context.RuntimeFSMController.parameters, typeof(FSMParameterData), true, true, true, true);

                reorderableList.headerHeight = 0;

                reorderableList.onAddDropdownCallback += OnAddDropdownCallback;
                reorderableList.onRemoveCallback += OnRemoveCallback;
                reorderableList.drawElementCallback += DrawElementCallback;

                reorderableList.onCanRemoveCallback += onCanRemoveCallback;
                reorderableList.onCanAddCallback += onCanRemoveCallback;
            }

            reorderableList.list = this.Context.RuntimeFSMController.parameters;

            GUILayout.BeginArea(rect);
            scrollView = GUILayout.BeginScrollView(scrollView);
            reorderableList.DoLayoutList();
            GUILayout.EndScrollView();
            GUILayout.EndArea();
        }

        public override void ProcessEvents()
        {
            base.ProcessEvents();
            if ( Event.current.type == EventType.MouseDown && Event.current.button == 0 && 
                position.Contains(Event.current.mousePosition)
                ) {
                this.Context.ClearSelections();
            }
        }

        public override void OnLostFocus()
        {
            base.OnLostFocus();
            isRenaming = false;
        }

        #endregion

        #region 方法
        public ParamLayer(FSMEditorWindow editorWindow):base(editorWindow) { 
            
        }

        // 添加
        private void OnAddDropdownCallback(Rect buttonRect, ReorderableList list) {
            GenericMenu menu = new GenericMenu();

            for (int i = 0; i < Enum.GetValues(typeof(ParameterType)).Length; i++)
            {
                ParameterType v =(ParameterType)Enum.GetValues(typeof(ParameterType)).GetValue(i);
                menu.AddItem(new GUIContent(v.ToString()), false, () => {

                    FSMParamterFactory.CreateParamter(this.Context.RuntimeFSMController, v);
                });
            }

            menu.ShowAsContext();
        }

        // 移除 
        private void OnRemoveCallback(ReorderableList list) {
            FSMParamterFactory.RemoveParamter(this.Context.RuntimeFSMController, list.index);
        }

        // 绘制每一条数据
        private void DrawElementCallback(Rect rect, int index, bool isActive, bool isFocused) {


            if (index < 0 || index >= this.Context.RuntimeFSMController.parameters.Count) return;

            FSMParameterData parameter = this.Context.RuntimeFSMController.parameters[index];

            if (parameter == null) return;
            paramLabelRect.Set(rect.x, rect.y, rect.width - param_value_width, rect.height);
            paramValueRect.Set(rect.x + rect.width - param_value_width + param_value_padding, rect.y + param_value_padding, param_value_width - param_value_padding, rect.height - param_value_padding * 2);

            if (Event.current.type == EventType.MouseDown && Event.current.button == 0
                && paramLabelRect.Contains(Event.current.mousePosition) && isFocused
                ) {
                isRenaming = true;
            }

            if (Event.current.type == EventType.MouseDown && Event.current.button == 0
                && !paramLabelRect.Contains(Event.current.mousePosition)&& 
                index == reorderableList.index) {
                //Debug.Log("取消重命名!");
                isRenaming = false;
            }

            // 按下回车键的时候 也需要取消重命名
            if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return)
            {

                EditorApplication.delayCall += () =>
                {
                    isRenaming = false;
                };

            }

            if (isRenaming && index == reorderableList.index)
            {
                // 绘制输入框
                EditorGUI.BeginChangeCheck();
                { 
                    newName = EditorGUI.DelayedTextField(paramLabelRect, parameter.name);
                }
                if ( EditorGUI.EndChangeCheck() ) {
                    //Debug.Log("修改参数名称:"+newName);
                    isRenaming = false;
                    FSMParamterFactory.RenameParamter(this.Context.RuntimeFSMController, parameter, newName);
                }

            }
            else { 
                GUI.Label(paramLabelRect, parameter.name);
            }


            switch (parameter.parameterType)
            {
                case ParameterType.Float:
                    parameter.Value = EditorGUI.FloatField(paramValueRect, parameter.Value);
                    break;
                case ParameterType.Int:
                    parameter.Value = EditorGUI.IntField(paramValueRect, (int)parameter.Value);
                    break;
                case ParameterType.Bool:
                    parameter.Value = EditorGUI.Toggle(paramValueRect, parameter.Value == 1) ? 1 : 0;
                    break;
            }

        }

        private bool onCanRemoveCallback(ReorderableList list) {
            return Application.isPlaying == false;
        }

        #endregion




    }

}

